package util

import (
	"github.com/DeanThompson/jpush-api-go-client"
	"github.com/DeanThompson/jpush-api-go-client/push"
)

const (
	appKey       = "532520c7edfe0af13e78d8fa"
	masterSecret = "087dc33e77959d64e2507351"
)

type pushAlert struct {
	Text       string
	RegisterId string
	Platform   string
}

var pushChn = make(chan pushAlert)

func init() {
	go func() {
		for {
			doPush()
		}
	}()
}

func Push(text, registerId string, p string) {
	pushChn <- pushAlert{Text: text, RegisterId: registerId, Platform: p}
}

func doPush() {
	entry := <-pushChn
	platform := push.NewPlatform()
	audience := push.NewAudience()
	audience.SetRegistrationId([]string{entry.RegisterId})
	notification := push.NewNotification("Golang.V3 Alert")
	client := jpush.NewJPushClient(appKey, masterSecret)
	options := push.NewOptions()
	if entry.Platform == Android_H5 {
		platform.Add("android")
		androidNotification := push.NewAndroidNotification(entry.Text)
		androidNotification.Title = "快来运消息推送通知"
		notification.Android = androidNotification
	} else {
		platform.Add("ios")
		iosNotification := push.NewIosNotification(entry.Text)
		iosNotification.Badge = 1
		notification.Ios = iosNotification
		options.ApnsProduction = true
	}

	options.TimeToLive = 86400
	payload := push.NewPushObject()
	payload.Platform = platform
	payload.Audience = audience
	payload.Notification = notification
	payload.Options = options
	if _, err := client.Push(payload); err != nil {
		GetLogger().Error("[util-push] - error:%s", err.Error())
	}

}
